<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/


namespace app\common\library\Authentication;

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Cloudauth\V20190307\Cloudauth;
use AlibabaCloud\SDK\Cloudauth\V20190307\Models\Mobile3MetaDetailVerifyRequest;
use AlibabaCloud\SDK\Cloudauth\V20190307\Models\Mobile3MetaDetailVerifyResponse;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Exception;

class Aliauth
{
    const biz_code_success = 1;
    const biz_code_success_message = '校验⼀致';
    const biz_code_fail = 2;
    const biz_code_fail_message = '校验不⼀致';
    const biz_code_not_exists = 3;
    const biz_code_not_exists_message = '查⽆记录';

    const SubCode_success = 101;
    const SubCode_success_message = '验证通过';
    const SubCode_fail_all_not_match = 201;
    const SubCode_fail_all_not_match_message = '⼿机号和姓名不⼀致，⼿机号和证件号不⼀致';

    const SubCode_fail_id_card_not_match = 202;
    const SubCode_fail_id_card_not_match_message = '⼿机号和姓名⼀致，⼿机号和证件号不⼀致';

    const SubCode_fail_name_not_match = 203;
    const SubCode_fail_name_not_match_message = '⼿机号和证件号⼀致，⼿机号和姓名不⼀致';


    const SubCode_fail_other_not_match = 204;
    const SubCode_fail_other_not_match_message = '其他不⼀致';

    const SubCode_fail_not_exists = 301;
    const SubCode_fail_not_exists_message = '查⽆记录';

    const IspName_CMCC = 'CMCC';
    const IspName_CMCC_message = '中国移动';

    const IspName_CUCC = 'CUCC';
    const IspName_CUCC_message = '中国联通';

    const IspName_CTCC = 'CTCC';
    const IspName_CTCC_message = '中国电信';

    const biz_code_arr =  [
        self::biz_code_success => [
            'value'=>self::biz_code_success,
            'message'=>self::biz_code_success_message,
        ],
        self::biz_code_fail => [
            'value'=>self::biz_code_fail,
            'message'=>self::biz_code_fail_message,
        ],
        self::biz_code_not_exists => [
            'value'=>self::biz_code_not_exists,
            'message'=>self::biz_code_not_exists_message,
        ]
    ];


    const biz_subCode_message =  [
        self::SubCode_success => [
            'value'=>self::SubCode_success,
            'message'=>self::SubCode_success_message,
        ],
        self::SubCode_fail_all_not_match => [
            'value'=>self::SubCode_fail_all_not_match,
            'message'=>self::SubCode_fail_all_not_match_message,
        ],
        self::SubCode_fail_id_card_not_match => [
            'value'=>self::SubCode_fail_id_card_not_match,
            'message'=>self::SubCode_fail_id_card_not_match_message,
        ],
        self::SubCode_fail_name_not_match => [
            'value'=>self::SubCode_fail_name_not_match,
            'message'=>self::SubCode_fail_name_not_match_message,
        ],
        self::SubCode_fail_other_not_match => [
            'value'=>self::SubCode_fail_other_not_match,
            'message'=>self::SubCode_fail_other_not_match_message,
        ],
        self::SubCode_fail_not_exists => [
            'value'=>self::SubCode_fail_not_exists,
            'message'=>self::SubCode_fail_not_exists_message,
        ],
    ];
    public static $failCode = 0;
    public static $successCode = 1;

    public static $failMessage = '认证失败';
    public static $successMessage = '认证成功';
    /**
     * createClient
     * @param string $endpoint
     * @return Cloudauth
     */
    private static function createClient(string $endpoint): Cloudauth
    {

        $aliAuthConfig = [
            'access_key_id'=>config('aliauth.accessKeyId') ?? 'LTAI5tM2sKUPrHzoqUYPLgkd',
            'access_key_secret'=>config('aliauth.accessKeySecret') ?? 'xNulvuBPTm6LTGd1VGultDiv84IZV4',
            'type'=>config('aliauth.type') ?? 'access_key',
        ];
        // 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
        // 本示例通过阿里云Credentials工具从环境变量中读取AccessKey，来实现API访问的身份验证。
        $credential = new Credential($aliAuthConfig);
        $config = new Config([
            // 使用credential配置凭证
            "credential" => $credential,
            // 设置HTTP代理。
            // "httpProxy" => "<http://xx.xx.xx.xx:xxxx>",
            // 设置HTTPS代理
            // "httpsProxy" => "<https://xx.xx.xx.xx:xxxx>",
            "endpoint" => $endpoint

        ]);
        return new Cloudauth($config);
    }


    /**
     * 实名认证
     * @param string $name
     * @param string $idcard
     * @param string $mobile
     * @return array
     */
    public static function main(string $name,string $idcard,string $mobile):array
    {
        try {
            $request = new Mobile3MetaDetailVerifyRequest([
                "paramType" => "normal",
                "userName" => $name,
                "identifyNum" => $idcard,
                "mobile" => $mobile,
            ]);
            // 推荐，支持服务路由。
            return self::mobile3MetaDetailVerifyAutoRoute($request);
        }catch (Exception $exception){
            return ['code'=>self::$failCode,'message'=>$exception->getMessage(),'data'=>null];
        }
    }

    /**
     * mobile3MetaDetailVerifyAutoRoute
     * @param Mobile3MetaDetailVerifyRequest $request
     * @return array|null
     */
    private static function mobile3MetaDetailVerifyAutoRoute(Mobile3MetaDetailVerifyRequest $request):array
    {
        $endpoints = [
            "cloudauth.cn-shanghai.aliyuncs.com",
            "cloudauth.cn-beijing.aliyuncs.com"
        ];
        foreach ($endpoints as $endpoint) {
            try {
                $response = self::mobile3MetaDetailVerify($endpoint, $request);
                if (Utils::equalNumber(500, $response->statusCode)) {
                    continue;
                }
                if (Utils::equalString("500", $response->body->code)) {
                    continue;
                }
                return ['code'=>$response->body->code,'message'=>$response->body->message,'data'=>(array)$response->body->resultObject];
            } catch (Exception $err) {
                return ['code'=>$err->getCode(),'message'=>$err->getMessage(),'data'=>null];
            }
        }
        return ['code'=>self::$failCode,'message'=>self::$failMessage];
    }

    /**
     * mobile3MetaDetailVerify
     * @param string $endpoint
     * @param Mobile3MetaDetailVerifyRequest $request
     * @return Mobile3MetaDetailVerifyResponse
     */
    private static function mobile3MetaDetailVerify(string $endpoint, Mobile3MetaDetailVerifyRequest $request): Mobile3MetaDetailVerifyResponse
    {
        $client = self::createClient($endpoint);
        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);
        $runtime->readTimeout = 5000;
        $runtime->connectTimeout = 5000;
        return $client->mobile3MetaDetailVerifyWithOptions($request, $runtime);
    }
}